package windows

import (
	"bytes"
	"fmt"
	"pass-tree/internal/logic/models"
	"pass-tree/internal/logic/repositories"
	"pass-tree/internal/logic/services"
	"strconv"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
)

type FormInputs struct {
	NameInput     *widget.Entry
	UsernameText  *widget.Entry
	PasswordInput *widget.Entry
	DescInput     *widget.Entry
	CustomContent *fyne.Container
	CustomInputs  map[string]CustomInputs
	SaveBtn       *widget.Button
	Container     fyne.CanvasObject // 原返回值
}
type CustomInputs struct {
	Id      *widget.Label
	Content *widget.Entry
}

// 添加窗口
func ShowAddWindow(app fyne.App, tabInfo services.TreeTabInfo, refresh func()) func() {
	return func() {
		w := app.NewWindow("添加")

		// w.SetFixedSize(true) // 设置固定大小，避免用户拖动改变大小

		// w.Minimizable = false // 去掉最小化按钮
		// w.SetMaximizable(false)

		makeUiLayout := makeUI(w)

		makeUiLayout.SaveBtn.OnTapped = func() {
			if makeUiLayout.NameInput.Text == "" {
				toast("请输入名称", w)
				return
			}
			pass := new(models.Password)
			pass.Category_id = tabInfo.Info.Id
			pass.Name = makeUiLayout.NameInput.Text
			pass.Username = makeUiLayout.UsernameText.Text
			pass.Password = makeUiLayout.PasswordInput.Text
			pass.Desc = makeUiLayout.DescInput.Text
			if len(makeUiLayout.CustomInputs) > 0 {
				var customInputType bytes.Buffer
				CustomContent := make([]models.Input_content, 0)
				for i, entry := range makeUiLayout.CustomInputs {
					customInputType.WriteString(i)
					customInputType.WriteString(",")
					CustomContent = append(CustomContent, models.Input_content{Input_type: i, Content: entry.Content.Text})
				}
				pass.CustomInputType = customInputType.String()[:len(customInputType.String())-1]
				pass.CustomContent = CustomContent
			}

			repositories.SavePassword(pass)
			refresh()
			w.Close()
		}
		w.SetContent(makeUiLayout.Container)

		initializeRunWindow(w)
	}
}

// 编辑窗口
func ShowEditWindow(tabInfo models.Password, refresh func()) func() {
	return func() {
		w := fyne.CurrentApp().NewWindow("编辑")
		// w.SetFixedSize(true) // 设置固定大小，避免用户拖动改变大小

		// w.Minimizable = false // 去掉最小化按钮
		// w.SetMaximizable(false)

		makeUiLayout := makeUI(w)
		makeUiLayout.NameInput.SetText(tabInfo.Name)
		makeUiLayout.UsernameText.SetText(tabInfo.Username)
		makeUiLayout.PasswordInput.SetText(tabInfo.Password)
		makeUiLayout.DescInput.SetText(tabInfo.Desc)

		for _, val := range tabInfo.CustomContent {
			customLabelText := widget.NewLabel(val.Input_type + ":  ")
			customLabelId := widget.NewLabel(fmt.Sprintf("%d", val.Id))
			customLabelId.Hide()
			customInput := widget.NewEntry()
			customInput.SetPlaceHolder("请输入" + val.Input_type)
			customInput.SetText(val.Content)
			//多行输入
			customInput.MultiLine = true
			customInput.Wrapping = 2 // 开启自动换行
			makeUiLayout.CustomInputs[val.Input_type] = CustomInputs{Id: customLabelId, Content: customInput}
			customLayout := container.NewBorder(nil, nil, customLabelText, customLabelId, customInput)
			makeUiLayout.CustomContent.Add(customLayout)
			makeUiLayout.CustomContent.Refresh() // 刷新容器以显示新添加的组件
		}

		makeUiLayout.SaveBtn.OnTapped = func() {
			pass := new(models.Password)
			pass.Id = tabInfo.Id
			pass.Name = makeUiLayout.NameInput.Text
			pass.Username = makeUiLayout.UsernameText.Text
			pass.Password = makeUiLayout.PasswordInput.Text
			pass.Desc = makeUiLayout.DescInput.Text
			if len(makeUiLayout.CustomInputs) > 0 {
				var customInputType bytes.Buffer
				CustomContent := make([]models.Input_content, 0)
				for i, entry := range makeUiLayout.CustomInputs {

					customInputType.WriteString(i)
					customInputType.WriteString(",")
					// 如果Id为空或文本为空，则设置num为0
					if entry.Id == nil || entry.Id.Text == "" {
						CustomContent = append(CustomContent, models.Input_content{Password_id: tabInfo.Id, Input_type: i, Content: entry.Content.Text})
					} else {
						num, err := strconv.Atoi(entry.Id.Text)
						if err != nil {
							return
						}
						CustomContent = append(CustomContent, models.Input_content{Id: num, Input_type: i, Content: entry.Content.Text})
					}
				}
				pass.CustomInputType = customInputType.String()[:len(customInputType.String())-1]
				pass.CustomContent = CustomContent
			}
			repositories.UpdatePassword(pass)
			refresh()
			w.Close()
		}
		w.SetContent(makeUiLayout.Container)

		initializeRunWindow(w)
	}
}

// 初始化运行窗口
func initializeRunWindow(w fyne.Window) fyne.Window {
	// start 监听主窗口的关闭事件
	// 前提是必须设置主窗口
	w.SetOnClosed(func() {
		w.Close()
	})
	// edn 监听主窗口的关闭事件

	// 设置窗口大小,
	w.Resize(fyne.NewSize(470, 500))
	w.CenterOnScreen()
	w.Show()
	// 确保子窗口显示在主窗口上方
	w.RequestFocus()
	return w
}

func makeUI(w fyne.Window) FormInputs {

	name := widget.NewLabel("名称:  ")
	nameInput := widget.NewEntry()
	// nameInput.FocusGained()//获取焦点，无效
	nameInput.SetPlaceHolder("请输入名称")
	//多行输入
	nameInput.MultiLine = true
	nameInput.Wrapping = 2 // 开启自动换行
	nameRow := container.NewBorder(nil, nil, name, nil, nameInput)

	username := widget.NewLabel("用户名:")
	usernameText := widget.NewEntry()
	usernameText.SetPlaceHolder("请输入用户名")
	//多行输入
	usernameText.MultiLine = true
	usernameText.Wrapping = 2 // 开启自动换行
	usernameRow := container.NewBorder(nil, nil, username, nil, usernameText)

	password := widget.NewLabel("密码:  ")
	passwordInput := widget.NewEntry()
	passwordInput.SetPlaceHolder("请输入密码")
	//多行输入
	passwordInput.MultiLine = true
	passwordInput.Wrapping = 2 // 开启自动换行
	passwordLayout := container.NewBorder(nil, nil, password, nil, passwordInput)

	desc := widget.NewLabel("描述:  ")
	descInput := widget.NewEntry()
	descInput.SetPlaceHolder("请输入描述")
	//多行输入
	descInput.MultiLine = true
	descInput.Wrapping = 2 // 开启自动换行
	descLayout := container.NewBorder(nil, nil, desc, nil, descInput)

	// 创建垂直布局容器
	content := container.NewVBox()

	// 创建存储所有输入框的切片
	var allInput = make(map[string]CustomInputs)

	addInputLabel := widget.NewLabel("输入框:")
	/* categoryList, nameList := ui.Services.GetCategoryList()
	selectCategoryBox := widget.NewSelect(nameList, func(val string) {

	}) */
	selectInputBox := widget.NewSelectEntry([]string{"appid", "appsecret", "url", "email", "clueid", "id"})
	selectInputBox.PlaceHolder = "请输入关键词或选择选项"
	//回车事件
	selectInputBox.OnSubmitted = func(val string) {
		customLabelText := widget.NewLabel(val + ":  ")
		customInput := widget.NewEntry()
		customInput.SetPlaceHolder("请输入" + val)
		//多行输入
		customInput.MultiLine = true
		customInput.Wrapping = 2 // 开启自动换行
		allInput[val] = CustomInputs{Content: customInput}
		customLayout := container.NewBorder(nil, nil, customLabelText, nil, customInput)
		content.Add(customLayout)
		content.Refresh() // 刷新容器以显示新添加的组件
	}
	addInputBtn := widget.NewButton(" 添加 ", func() {
		if selectInputBox.Text == "" {
			toast("请输入关键词", w)
			return
		}
		customLabelText := widget.NewLabel(selectInputBox.Text + ":  ")
		customInput := widget.NewEntry()
		customInput.SetPlaceHolder("请输入" + selectInputBox.Text)
		//多行输入
		customInput.MultiLine = true
		customInput.Wrapping = 2 // 开启自动换行
		// 延迟100毫秒后获取焦点
		go func() {
			time.Sleep(time.Millisecond * 100)
			customInput.FocusGained()
		}()
		allInput[selectInputBox.Text] = CustomInputs{Content: customInput}
		customLayout := container.NewBorder(nil, nil, customLabelText, nil, customInput)
		content.Add(customLayout)
		content.Refresh()          // 刷新容器以显示新添加的组件
		selectInputBox.SetText("") // 清空输入框
		selectInputBox.Refresh()
	})
	addInputLayout := container.NewBorder(nil, nil, addInputLabel, addInputBtn, selectInputBox)

	saveBtn := widget.NewButton(" 保存 ", func() {})

	cancelBtn := widget.NewButton(" 取消 ", func() {
		w.Close()
	})

	bodyLayout := container.New(layout.NewVBoxLayout(), nameRow, usernameRow, passwordLayout, descLayout, addInputLayout, content)
	//保存按钮
	saveBtnLayout := container.NewBorder(nil, nil, nil, container.New(layout.NewHBoxLayout(), cancelBtn, saveBtn), nil)

	// 使用 BorderLayout，滚动区域在中心，按钮在底部
	allLayout := container.NewBorder(
		nil,           // 顶部无元素
		saveBtnLayout, // 底部放置按钮
		nil,           // 左侧无元素
		nil,           // 右侧无元素
		container.NewVScroll(container.NewStack(bodyLayout)), // 中心区域放置滚动内容
	)
	return FormInputs{
		NameInput:     nameInput,
		UsernameText:  usernameText,
		PasswordInput: passwordInput,
		DescInput:     descInput,
		// 创建垂直布局容器
		CustomContent: content,
		CustomInputs:  allInput,
		SaveBtn:       saveBtn,
		Container:     allLayout,
	}
}

// 提示弹窗
func toast(title string, win fyne.Window) {
	infoDialog := dialog.NewInformation("提示", title, win)

	// 显示信息对话框
	infoDialog.Show()
}
